package org.jeecg.modules.performance.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.DateTimeUtil;
import org.jeecg.modules.content.mapper.ConContentTemplateMapper;
import org.jeecg.modules.content.model.ConContentTemplateModel;
import org.jeecg.modules.performance.Model.PerformanceConfigModel;
import org.jeecg.modules.performance.Model.TaskBaseModel;
import org.jeecg.modules.performance.Model.UserPerforInfoModel;
import org.jeecg.modules.performance.Model.UserPerforModel;
import org.jeecg.modules.performance.entity.*;
import org.jeecg.modules.performance.mapper.PerformanceConfigMapper;
import org.jeecg.modules.performance.mapper.PerformanceMonthDepartMapper;
import org.jeecg.modules.performance.mapper.PerformanceMonthMapper;
import org.jeecg.modules.performance.service.*;
import org.jeecg.modules.publish.entity.ThirdReadNum;
import org.jeecg.modules.publish.mapper.ThirdReadNumMapper;
import org.jeecg.modules.publish.service.IThirdReadNumService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysDictItem;
import org.jeecg.modules.system.mapper.SysDepartMapper;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.jeecg.modules.system.service.ISysDictItemService;
import org.jeecg.modules.task.mapper.TaskInfoBaseMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CalculatePerforServiceImpl implements ICalculatePerforService {
    @Autowired
    private PerformanceConfigServiceImpl performanceConfigServiceImpl;
   @Autowired
   private IPerformanceMonthTaskDetailService performanceMonthTaskDetailService;
   @Autowired
   private IPerformanceMonthPostDetailService performanceMonthPostDetailService;
   @Autowired
   private IPerformanceMonthDetailService performanceMonthDetailService;
   @Autowired
   private IPerformanceMonthDepartService  performanceMonthDepartService;

   @Autowired
   private IPerformanceUserLogService performanceUserLogService;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private TaskInfoBaseMapper tasTaskInfoMapper;
    @Autowired
    private PerformanceConfigMapper performanceConfigMapper;
    @Autowired
    private PerformanceMonthMapper performanceMonthMapper;
    @Autowired
    private SysDepartMapper sysDepartMapper;
    @Autowired
    private ISysDictItemService iSysDictItemService;
    @Autowired
    private ConContentTemplateMapper conContentTemplateMapper;
    @Autowired
    private PerformanceMonthDepartMapper performanceMonthDepartMapper;
    @Autowired
    private IThirdReadNumService thirdReadNumService;
    @Autowired
    private ThirdReadNumMapper thirdReadNumMapper;

    @Override
    public List<PerformanceMonthDetail> countPostPerfor() {
        Page<UserPerforModel> page = new Page<UserPerforModel>(1, Integer.MAX_VALUE);

        List<UserPerforModel> records = performanceConfigServiceImpl.getUserPerformanceList(page, new UserPerforModel()).getRecords();
        List<PerformanceMonthDetail> performanceMonthDetailList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(records)) {
            for (UserPerforModel record : records) {
                PerformanceMonthDetail performanceMonthDetail = new PerformanceMonthDetail();
                performanceMonthDetail.setCreateTime(new Date());
                performanceMonthDetail.setPostPreforName(record.getPostPerforms());
                performanceMonthDetail.setPostAmount(Float.valueOf(record.getPostValue()));
                performanceMonthDetail.setUserId(record.getUserId());
                performanceMonthDetail.setDepartId(record.getDepartId());
                if(record.getFixSalary() == null){
                    performanceMonthDetail.setSalaryAmount(0f);

                }else {
                    performanceMonthDetail.setSalaryAmount(record.getFixSalary());

                }
                performanceMonthDetailList.add(performanceMonthDetail);
            }
        }

        return performanceMonthDetailList;
    }


    /**
     * 计算阅读量绩效
     *
     * @param startTime
     * @param endTime
     * @return
     */

    private List<PerformanceMonthTaskDetail> countReadPerfor(String startTime, String endTime) {


        List<ThirdReadNum> list = thirdReadNumMapper.getList(startTime, endTime);
        List<PerformanceMonthTaskDetail> performanceMonthTaskDetailList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {

            QueryWrapper<PerformanceConfig> queryWrapper = new QueryWrapper<>();

            QueryWrapper<PerformanceConfig> configueryWrapper = new QueryWrapper<>();
            configueryWrapper.eq("type", "other");
            configueryWrapper.isNotNull("code");
            configueryWrapper.orderByDesc("score");
            List<PerformanceConfig> performanceConfigs = performanceConfigMapper.selectList(configueryWrapper);
            for (ThirdReadNum thirdReadNum : list) {

                  for (PerformanceConfig performanceConfig : performanceConfigs) {
                      if (thirdReadNum.getType() == 1) {
                        if (performanceConfig.getCode().contains("wx")) {
                            if (performanceConfig.getCondit() == 2) {

                                //大于
                                if (thirdReadNum.getReadNum() > Integer.valueOf(performanceConfig.getValueStart())) {
                                    thirdReadNum.setScore(Float.valueOf(performanceConfig.getScore()));
                                    break;
                                }
                            }
                            if (performanceConfig.getCondit() == 3) {
                                //大于等于 且小于
                                if (thirdReadNum.getReadNum() >= Integer.valueOf(performanceConfig.getValueStart()) && thirdReadNum.getReadNum() < Integer.valueOf(performanceConfig.getValueEnd())) {
                                    thirdReadNum.setScore(Float.valueOf(performanceConfig.getScore()));
                                    break;
                                }
                            }
                            if (performanceConfig.getCondit() == 1) {
                                //小于等于
                                if (thirdReadNum.getReadNum() <= Integer.valueOf(performanceConfig.getValueEnd())) {
                                    thirdReadNum.setScore(Float.valueOf(performanceConfig.getScore()));
                                    break;
                                }
                            }
                        }
                    } else if (thirdReadNum.getType()==2) {
                          if (performanceConfig.getCode().contains("wb")) {
                              if (performanceConfig.getCondit() == 2) {

                                  //大于
                                  if (thirdReadNum.getReadNum() > Integer.valueOf(performanceConfig.getValueStart())) {
                                      thirdReadNum.setScore(Float.valueOf(performanceConfig.getScore()));
                                      break;
                                  }
                              }
                              if (performanceConfig.getCondit() == 3) {
                                  //大于等于 且小于
                                  if (thirdReadNum.getReadNum() >= Integer.valueOf(performanceConfig.getValueStart()) && thirdReadNum.getReadNum() < Integer.valueOf(performanceConfig.getValueEnd())) {
                                      thirdReadNum.setScore(Float.valueOf(performanceConfig.getScore()));
                                      break;
                                  }
                              }
                              if (performanceConfig.getCondit() == 1) {
                                  //小于等于
                                  if (thirdReadNum.getReadNum() <= Integer.valueOf(performanceConfig.getValueEnd())) {
                                      thirdReadNum.setScore(Float.valueOf(performanceConfig.getScore()));
                                      break;
                                  }
                              }
                          }

                    } else {
                          if (performanceConfig.getCode().contains("dy")) {
                              //抖音
                              if (performanceConfig.getCondit() == 2) {

                                  //大于
                                  if (thirdReadNum.getReadNum() > Integer.valueOf(performanceConfig.getValueStart())) {
                                      thirdReadNum.setScore(Float.valueOf(performanceConfig.getScore()));
                                      break;
                                  }
                              }
                              if (performanceConfig.getCondit() == 3) {
                                  //大于等于 且小于
                                  if (thirdReadNum.getReadNum() >= Integer.valueOf(performanceConfig.getValueStart()) && thirdReadNum.getReadNum() < Integer.valueOf(performanceConfig.getValueEnd())) {
                                      thirdReadNum.setScore(Float.valueOf(performanceConfig.getScore()));
                                      break;
                                  }
                              }
                              if (performanceConfig.getCondit() == 1) {
                                  //小于等于
                                  if (thirdReadNum.getReadNum() <= Integer.valueOf(performanceConfig.getValueEnd())) {
                                      thirdReadNum.setScore(Float.valueOf(performanceConfig.getScore()));
                                      break;
                                  }
                              }
                          }
                      }
                }

            }
            QueryWrapper<SysDictItem> dicQueryWrapper = new QueryWrapper<>();
            dicQueryWrapper.eq("item_text", "union_write");
            SysDictItem item = iSysDictItemService.getOne(dicQueryWrapper);
            for (ThirdReadNum thirdReadNum : list) {
                //属于联合撰稿人；
                List<String> userIds = tasTaskInfoMapper.selectUnionIdsByContenId(thirdReadNum.getContentId());
                if (!CollectionUtils.isEmpty(userIds)) {
                    float count = userIds.size();
                    for (String userId : userIds) {
                        PerformanceMonthTaskDetail performanceMonthTaskDetail = new PerformanceMonthTaskDetail();
                        performanceMonthTaskDetail.setContentId(thirdReadNum.getContentId());
                        performanceMonthTaskDetail.setUserId(userId);
                        if (item.getItemValue().equals("1")) {
                            //平分，  存在精度丢失

                            performanceMonthTaskDetail.setOtherScore(thirdReadNum.getScore() / count);
                        } else {
                            performanceMonthTaskDetail.setOtherScore(thirdReadNum.getScore());
                        }
                        performanceMonthTaskDetail.setTaskId(thirdReadNum.getTaskId());
                        performanceMonthTaskDetailList.add(performanceMonthTaskDetail);
                    }

                }


            }
            Map<String, PerformanceMonthTaskDetail> map = new HashMap<>();
            for (PerformanceMonthTaskDetail performanceMonthTaskDetail : performanceMonthTaskDetailList) {
                PerformanceMonthTaskDetail detail = map.get(performanceMonthTaskDetail.getUserId());
                if (detail == null) {
                    map.put(performanceMonthTaskDetail.getUserId(), performanceMonthTaskDetail);
                } else {
                    detail.setOtherScore(detail.getOtherScore() + performanceMonthTaskDetail.getOtherScore());
                }
            }
            performanceMonthTaskDetailList = new ArrayList<>(map.values());
        }
        // performanceMonthTaskDetailList重后

        return performanceMonthTaskDetailList;
    }


    /**
     * 计算时效绩效
     *
     * @param performanceMonth 存入 spreadScore taskId userId
     * @return
     */

    private List<PerformanceMonthTaskDetail> countTimePerformance(PerformanceMonth performanceMonth) {
        List<PerformanceMonthTaskDetail> performanceMonthTaskDetailList = new ArrayList<>();

        String firstDay = performanceMonth.getStartTime()+" 00:00:00";

        String lastDay = performanceMonth.getEndTime()+" 23:59:59";
         List<TaskBaseModel> taskBaseModelList = tasTaskInfoMapper.getPerforTask(firstDay, lastDay);

        QueryWrapper<PerformanceConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", "time");
        Map<String, PerformanceConfig> configMap = performanceConfigMapper.selectList(queryWrapper).stream().collect(Collectors.toMap(PerformanceConfig::getCode, x -> x));

        if (!CollectionUtils.isEmpty(taskBaseModelList)) {

            Map<String, List<TaskBaseModel>> collect = taskBaseModelList.stream().collect(Collectors.groupingBy(TaskBaseModel::getTaskId));
            for (String s : collect.keySet()) {
                List<TaskBaseModel> list = collect.get(s);

            for(int i=0 ;i< list.size();i++){
                if(i>=1){
                    TaskBaseModel taskBaseModel=    list.get(i);
                    String performType = taskBaseModel.getPerformType();
                    System.out.println(JSON.toJSON(taskBaseModel).toString());
                    if(!StringUtils.isEmpty(performType)){
                        PerformanceMonthTaskDetail performanceMonthTaskDetail  = new PerformanceMonthTaskDetail();
                        performanceMonthTaskDetail.setTaskId(taskBaseModel.getTaskId());
                        performanceMonthTaskDetail.setUserId(taskBaseModel.getUserId());
                        PerformanceConfig perfor = configMap.get(performType);
                        Long aLong = DateTimeUtil.betweenHour(list.get(i - 1).getCreateTime(), taskBaseModel.getCreateTime());

                        if (Float.valueOf(aLong) <= Float.valueOf(perfor.getValueStart())) {
                            performanceMonthTaskDetail.setTimeScore(Float.valueOf(perfor.getScore()));
                        } else {
                            performanceMonthTaskDetail.setTimeScore(Float.valueOf(perfor.getOverScore()));

                        }
                        performanceMonthTaskDetailList.add(performanceMonthTaskDetail);
                    }
                }
            }

            }
        }

        return  performanceMonthTaskDetailList;
    }


    /**
     * 计算传播绩效
     * @param performanceMonth
     * @return
     */
    private   List<PerformanceMonthTaskDetail> countSparedPerformance(PerformanceMonth performanceMonth){
       //查看配置传播绩效联合撰写人是否是平摊
       //
        List<PerformanceMonthTaskDetail> performanceMonthTaskDetailList = new ArrayList<>();
        QueryWrapper<SysDictItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("item_text","union_write");
        SysDictItem item = iSysDictItemService.getOne(queryWrapper);
        Page<ConContentTemplateModel> page = new Page<ConContentTemplateModel>(1, Integer.MAX_VALUE);
        ConContentTemplateModel conContentTemplateModel = new ConContentTemplateModel();
        conContentTemplateModel.setStartTime(performanceMonth.getStartTime()+" 00:00:00");
        conContentTemplateModel.setEndTime(performanceMonth.getEndTime()+" 23:59:59");
        List<ConContentTemplateModel> perList = conContentTemplateMapper.getPerList(page, conContentTemplateModel);
        //查出当前文章和对应的关联人
        if(!CollectionUtils.isEmpty(perList)){

            for (ConContentTemplateModel contentTemplateModel : perList) {


                List<String> userIds = tasTaskInfoMapper.selectUnionIds(contentTemplateModel.getContentNo());
                if(!CollectionUtils.isEmpty(userIds)){
                    float   count = userIds.size();
                    for (String userId : userIds) {
                        PerformanceMonthTaskDetail  performanceMonthTaskDetail = new PerformanceMonthTaskDetail();
                        performanceMonthTaskDetail.setContentId(contentTemplateModel.getContentId());
                        performanceMonthTaskDetail.setUserId(userId);
                        if(item.getItemValue().equals("1")){
                            //平分，  存在精度丢失

                            performanceMonthTaskDetail.setSpreadScore(contentTemplateModel.getScore()/count)  ;
                        }else{
                            performanceMonthTaskDetail.setSpreadScore(contentTemplateModel.getScore());
                        }
                        performanceMonthTaskDetail.setTaskId(contentTemplateModel.getTaskId());
                        performanceMonthTaskDetailList.add(performanceMonthTaskDetail);

                    }

                }


            }
        }

        return  performanceMonthTaskDetailList;
    }

    private  void checkDate(PerformanceMonth performanceMonth){
        QueryWrapper<PerformanceMonth> queryWrapper = new QueryWrapper<>();
        queryWrapper.gt("end_time",performanceMonth.getStartTime());
        List<PerformanceMonth> performanceMonths = performanceMonthMapper.selectList(queryWrapper);
        if(!CollectionUtils.isEmpty(performanceMonths)){
            throw  new JeecgBootException("请勿重复创建同一周期的绩效考评数据");
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public void chaifenJixiao(PerformanceMonth performanceMonth){
        //验证时间内是否计算过绩效
        checkDate( performanceMonth);




        QueryWrapper<SysDictItem> fixWrapper = new QueryWrapper<>();
        fixWrapper.eq("item_text","fix_salary");
        SysDictItem item = iSysDictItemService.getOne(fixWrapper);
        Boolean fixFlag = false;
        if(item.getItemValue().equals("2")){
            fixFlag = true;
        }
        if(fixFlag) {
            //固定薪资不参与绩效
            performanceMonth.setFixStatus(2);
        }
        //插入绩效表信息
        performanceMonthMapper.insert(performanceMonth);
        // '岗位薪资金额','本月奖金金额', `'动态调整金额',`'基础薪资（固定+岗位） 回填

        //计算时效绩效和传播绩效 存放 performanceMonthTaskDetailList
        List<PerformanceMonthTaskDetail> timeList = this.countTimePerformance(performanceMonth);
        List<PerformanceMonthTaskDetail> sparedList = this.countSparedPerformance(performanceMonth);
        List<PerformanceMonthTaskDetail> readList = countReadPerfor(performanceMonth.getStartTime(), performanceMonth.getEndTime());

        //合并绩效结果
        List<PerformanceMonthTaskDetail> performanceMonthTaskDetailList = combineList(timeList, sparedList, readList);

        //计算岗位绩效和固定工资绩效 并保存 计算 总的时效绩效和传播绩效
        List<UserPerforInfoModel> baseUser = sysUserMapper.getBaseUser();
        List<PerformanceMonthDetail> performanceMonthDetailList = new ArrayList<>();
        List<PerformanceMonthDetail> performanceMonthDetails = this.countPostPerfor();


        Map<String, PerformanceMonthDetail> postMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(performanceMonthDetails)) {
            postMap = performanceMonthDetails.stream().collect(Collectors.toMap(PerformanceMonthDetail::getUserId, x -> x));

        }
        Float  totalFixedSalary = 0f;

        List<PerformanceUserLog> performanceUserLogList = new ArrayList<>();
        for (UserPerforInfoModel userPerforInfoModel : baseUser) {
            Float timeScore = 0f;
            Float spreadScore = 0f;
            Float otherScore =0f;
            for (PerformanceMonthTaskDetail performanceMonthTaskDetail : performanceMonthTaskDetailList) {
                if(performanceMonthTaskDetail.getUserId().equals(userPerforInfoModel.getUserId())){
                    //固定参与绩效考核或者固定薪资参不参与绩效考合 并且没有配置固定薪资
                  if(userPerforInfoModel.getFixType()==null){
                      //数据库没配固定薪资是否参与绩效 默认参与绩效计算
                      timeScore += performanceMonthTaskDetail.getTimeScore();
                      spreadScore += performanceMonthTaskDetail.getSpreadScore();
                      otherScore += performanceMonthTaskDetail.getOtherScore();
                  }else{
                      if(!fixFlag  ||(fixFlag  && userPerforInfoModel.getFixType()== 2)) {
                          //固定薪资参与绩效考合

                          timeScore += performanceMonthTaskDetail.getTimeScore();
                          spreadScore += performanceMonthTaskDetail.getSpreadScore();
                          otherScore += performanceMonthTaskDetail.getOtherScore();

                      } else {
                          //固定薪资不参与绩效考合 ，是固定薪资  或者固定薪资没配的
                          performanceMonthTaskDetail.setTimeScore(0f);
                          performanceMonthTaskDetail.setSpreadScore(0f);
                          performanceMonthTaskDetail.setOtherScore(0f);

                      }
                  }


                }
            }
            PerformanceMonthDetail performanceMonthDetail = new PerformanceMonthDetail();
            performanceMonthDetail.setUserId(userPerforInfoModel.getUserId());
            performanceMonthDetail.setDepartId(userPerforInfoModel.getDepartId());
            performanceMonthDetail.setPerforMonthId(performanceMonth.getId());
            performanceMonthDetail.setSpreadScore(spreadScore);
            performanceMonthDetail.setTimeScore(timeScore);
            performanceMonthDetail.setOtherScore(otherScore);
            if(userPerforInfoModel.getFixType() !=null && userPerforInfoModel.getFixType().equals(1)){
                //启用固定薪资
                performanceMonthDetail.setSalaryAmount(userPerforInfoModel.getFixSalary());

                totalFixedSalary += userPerforInfoModel.getFixSalary();
                if(fixFlag){
                    //固定薪资不参与考核  如果启用 其绩效不考核
                    performanceMonthDetail.setCheckStatus(2);
                }


            }else {
                performanceMonthDetail.setSalaryAmount(0f);


            }
            PerformanceMonthDetail detail = postMap.get(userPerforInfoModel.getUserId());
                    if (detail != null) {
                        performanceMonthDetail.setPostPreforName(detail.getPostPreforName());
                        performanceMonthDetail.setPostAmount(detail.getPostAmount());
                        totalFixedSalary += detail.getPostAmount();
                       // totalFixedSalary += detail.getSalaryAmount();
                    }
                    performanceMonthDetailService.save(performanceMonthDetail);
                    performanceMonthDetailList.add(performanceMonthDetail);



                    //注意  总分值对应的总金额没入
            QueryWrapper<PerformanceConfig> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("type", "post");
            //查询岗位业绩
            Page<UserPerforModel> page = new Page<UserPerforModel>(1, Integer.MAX_VALUE);

            List<UserPerforModel> userPerformanceList = performanceConfigMapper.getUserPerformanceList(page, new UserPerforModel());
            List<PerformanceMonthPostDetail> performanceMonthPostDetails = new ArrayList<>();

            //插入岗位绩效详情表和日志表
            for (UserPerforModel perforModel : userPerformanceList) {

                if (perforModel.getUserId().equals(performanceMonthDetail.getUserId())) {
                    if (!CollectionUtils.isEmpty(perforModel.getPerformanceConfigModelList())) {
                        for (PerformanceConfigModel performanceConfigModel : perforModel.getPerformanceConfigModelList()) {
                            PerformanceMonthPostDetail performanceMonthPostDetail = new PerformanceMonthPostDetail();

                            performanceMonthPostDetail.setDetailId(performanceMonthDetail.getId());
                            performanceMonthPostDetail.setUserId(perforModel.getUserId());
                            performanceMonthPostDetail.setName(performanceConfigModel.getName());
                            performanceMonthPostDetail.setPostAmount(Float.valueOf(performanceConfigModel.getScore()));
                            performanceMonthPostDetails.add(performanceMonthPostDetail);

                            PerformanceUserLog performanceUserLog = new PerformanceUserLog();
                            performanceUserLog.setLogName(performanceConfigModel.getName());
                            performanceUserLog.setAdjustAmount(Float.valueOf(performanceConfigModel.getScore()));
                            performanceUserLog.setAdjustType(4);
                            performanceUserLog.setOpType(5);
                            performanceUserLog.setDetailId(performanceMonthDetail.getId());
                            performanceUserLogList.add(performanceUserLog);

                           // performanceUserLogService.save(performanceUserLog);

                        }
                    }
                    //插入固定工资
                    if (userPerforInfoModel.getFixType() !=null && userPerforInfoModel.getFixType().equals(1)) {
                        PerformanceMonthPostDetail performanceMonthPostDetail = new PerformanceMonthPostDetail();
                        performanceMonthPostDetail.setDetailId(performanceMonthDetail.getId());
                        performanceMonthPostDetail.setUserId(perforModel.getUserId());
                        performanceMonthPostDetail.setName("固定工资");
                        performanceMonthPostDetail.setPostAmount(Float.valueOf(userPerforInfoModel.getFixSalary()));
                        performanceMonthPostDetails.add(performanceMonthPostDetail);

                        //todo 插入岗位和固定工资日志表
                        PerformanceUserLog performanceUserLog = new PerformanceUserLog();
                        performanceUserLog.setLogName("固定工资");
                        performanceUserLog.setAdjustAmount(performanceMonthPostDetail.getPostAmount());
                        performanceUserLog.setAdjustType(1);
                        performanceUserLog.setOpType(5);
                        performanceUserLog.setDetailId(performanceMonthDetail.getId());
                        performanceUserLogList.add(performanceUserLog);
                       // performanceUserLogService.save(performanceUserLog);
                    }
                }


            }


            performanceMonthPostDetailService.saveBatch(performanceMonthPostDetails);
            }


       //插入绩效部门表 一级部门
        QueryWrapper<SysDepart> sysDepartQueryWrapper = new QueryWrapper<>();
        sysDepartQueryWrapper.eq("org_type",1).eq("del_flag",0);
        List<SysDepart> sysDeparts = sysDepartMapper.selectList(sysDepartQueryWrapper);
        //插入部门表基础信息
        List<PerformanceMonthDepart> performanceMonthDepartList = new ArrayList<>();
        for (SysDepart sysDepart : sysDeparts) {
            PerformanceMonthDepart performanceMonthDepart = new PerformanceMonthDepart();
            performanceMonthDepart.setDepartId(sysDepart.getId());
            performanceMonthDepart.setName(performanceMonth.getName()+"("+sysDepart.getDepartName()+")");
            performanceMonthDepart.setPerforMonthId(performanceMonth.getId());
            performanceMonthDepartList.add(performanceMonthDepart);
        }
        performanceMonthDepartService.saveBatch(performanceMonthDepartList);


        Float totalScore = 0f;
        Map<String, String> collect = performanceMonthDetailList.stream().collect(Collectors.toMap(x -> x.getUserId(), x -> x.getId()));
        for (PerformanceMonthTaskDetail performanceMonthTaskDetail : performanceMonthTaskDetailList) {
            performanceMonthTaskDetail.setDetailId(collect.get(performanceMonthTaskDetail.getUserId()));
            totalScore += performanceMonthTaskDetail.getSpreadScore() + performanceMonthTaskDetail.getTimeScore() + performanceMonthTaskDetail.getOtherScore();
        }
        //保存时效绩效和传播绩效
        performanceMonthTaskDetailService.saveBatch(performanceMonthTaskDetailList);
        Float perAmount = 0f;
        Float perforAmount =  performanceMonth.getFenpeiAmount() - totalFixedSalary;

        if(perforAmount >0){
            if(totalScore>0){
                perAmount = perforAmount/totalScore;

            }else {
                perAmount =0f;
            }
            //这里的分配金额要减去基础薪资的总金额

        }else {
            throw  new JeecgBootException("奖金金额设置低于基础薪资支出");
        }
       // List<PerformanceUserLog> performanceUserLogList = new ArrayList<>();
        float  totalAmount = 0f;
        for (PerformanceMonthDetail performanceMonthDetail : performanceMonthDetailList) {
            totalScore = performanceMonthDetail.getTimeScore()+performanceMonthDetail.getSpreadScore()+performanceMonthDetail.getOtherScore();
            BigDecimal b  =   new  BigDecimal(totalScore*perAmount);

            float   scoreAmount   =  b.setScale(2,  BigDecimal.ROUND_DOWN).floatValue();
            totalAmount += scoreAmount;
            performanceMonthDetail.setScoreAmount(scoreAmount);

            PerformanceUserLog performanceUserLog = new PerformanceUserLog();
            performanceUserLog.setLogName("绩效薪资");
            performanceUserLog.setAdjustAmount(performanceMonthDetail.getScoreAmount());
            performanceUserLog.setAdjustType(1);
            performanceUserLog.setOpType(3);
            performanceUserLog.setDetailId(performanceMonthDetail.getId());
            performanceUserLogList.add(performanceUserLog);
        }
//        if( performanceMonth.getFenpeiAmount()-totalAmount>0){
//            performanceMonthDetail
//        }

        performanceUserLogService.saveBatch(performanceUserLogList);
        performanceMonthDetailService.saveOrUpdateBatch(performanceMonthDetailList);

    }


    private List<PerformanceMonthTaskDetail> combineList(List<PerformanceMonthTaskDetail> timeList, List<PerformanceMonthTaskDetail> sparedList, List<PerformanceMonthTaskDetail> readList) {

        timeList.addAll(sparedList);
        timeList.addAll(readList);
        Map<String, PerformanceMonthTaskDetail> resultMap = new HashMap<>();
        if (CollectionUtils.isEmpty(timeList)) {
            return timeList;
        }


        for (PerformanceMonthTaskDetail performanceMonthTaskDetail : timeList) {
            String key = performanceMonthTaskDetail.getUserId() + "-" + performanceMonthTaskDetail.getTaskId();
            PerformanceMonthTaskDetail detail = resultMap.get(key);

            if(detail == null){

                 resultMap.put(key,performanceMonthTaskDetail);
            } else {
                if (performanceMonthTaskDetail.getTimeScore() != null && performanceMonthTaskDetail.getTimeScore() > 0) {
                    detail.setTimeScore(performanceMonthTaskDetail.getTimeScore());

                }

                if (performanceMonthTaskDetail.getSpreadScore() != null && performanceMonthTaskDetail.getSpreadScore() > 0) {
                    detail.setSpreadScore(performanceMonthTaskDetail.getSpreadScore());

                }
                if (performanceMonthTaskDetail.getOtherScore() != null && performanceMonthTaskDetail.getOtherScore() > 0) {
                    detail.setOtherScore(performanceMonthTaskDetail.getOtherScore());

                }
                if (performanceMonthTaskDetail.getContentId() != null) {
                    detail.setContentId(performanceMonthTaskDetail.getContentId());
                }
            }
        }
        return resultMap.values().stream().collect(Collectors.toList());
    }

    @Override
    public void countTimePerfor(String userName) {

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void countPerfor() {
//        //一次性查询所有用户
//        List<SysUser> baseUser = sysUserMapper.getBaseUser();
//
//        Map<String, List<SysUser>> groupBy = baseUser.stream().collect(Collectors.groupingBy(SysUser::getDepartIds));
//
//        //一次性查询配置的岗位绩效
//        //获取前一个月第一天
//        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
//        Calendar calendar1 = Calendar.getInstance();
//        calendar1.add(Calendar.MONTH, -1);
//        calendar1.set(Calendar.DAY_OF_MONTH, 1);
//        String firstDay = df.format(calendar1.getTime())+" 00:00:00";
//        //获取前一个月最后一天
//        Calendar calendar2 = Calendar.getInstance();
//        calendar2.set(Calendar.DAY_OF_MONTH, 0);
//        String lastDay = df.format(calendar2.getTime())+" 23:59:59";
//
//        List<TaskBaseModel> taskBaseModelList = tasTaskInfoMapper.getPerforTask(firstDay, lastDay);
//
//        QueryWrapper<PerformanceConfig> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("type", "time");
//        Map<String, PerformanceConfig> configMap = performanceConfigMapper.selectList(queryWrapper).stream().collect(Collectors.toMap(PerformanceConfig::getCode, x -> x));
//        PerformanceConfig edit = configMap.get("edit");
//        PerformanceConfig check = configMap.get("check");
//        if (!CollectionUtils.isEmpty(taskBaseModelList)) {
//            for (TaskBaseModel taskBaseModel : taskBaseModelList) {
//                Integer editStartKye = 1;
//                Integer editEndKey = 20;
//                Integer checkStartKey = 21;
//                Integer checkEndKey = 40;
//                if (taskBaseModel.getTaskType() == 3) {
//                    //选题有采访
//                    editStartKye = editStartKye + 20;
//                    editEndKey = editEndKey + 20;
//                    checkStartKey = checkStartKey + 20;
//                    checkEndKey = checkEndKey + 20;
//
//                }
//
//                if(taskBaseModel.getFromKey() !=null){
//                    //编辑
//                    if (editStartKye <= taskBaseModel.getFromKey() && taskBaseModel.getFromKey() <= editEndKey) {
//
//                        if (Float.valueOf(taskBaseModel.getDuration()) / 1000f / 60f <= Float.valueOf(edit.getValueStart())) {
//                            taskBaseModel.setScore(Float.valueOf(edit.getScore()));
//                        } else {
//                            taskBaseModel.setScore(Float.valueOf(edit.getOverScore()));
//
//                        }
//                    }
//
//                    //审核
//                    if (checkStartKey <= taskBaseModel.getFromKey() && taskBaseModel.getFromKey() <= checkEndKey) {
//
//                        if (taskBaseModel.getDuration() / 1000f / 60f <= Float.valueOf(check.getValueStart())) {
//                            taskBaseModel.setScore(Float.valueOf(check.getScore()));
//                        } else {
//                            taskBaseModel.setScore(Float.valueOf(check.getOverScore()));
//
//                        }
//                    }
//                }
//
//            }
//        }
//        //taskBaseModelList 去重合并
//        Map<String, TaskBaseModel> taskMap = new HashMap<>();
//        for (TaskBaseModel taskBaseModel : taskBaseModelList) {
//            TaskBaseModel mapModel = taskMap.get(taskBaseModel.getAssignee());
//            if (mapModel == null) {
//                taskMap.put(taskBaseModel.getAssignee(), taskBaseModel);
//            } else {
//                mapModel.setScore(mapModel.getScore() + taskBaseModel.getScore());
//            }
//        }
//        List<PerformanceMonthDetail> performanceMonthDetails = this.countPostPerfor();
//        Map<String, PerformanceMonthDetail> postMap = performanceMonthDetails.stream().collect(Collectors.toMap(PerformanceMonthDetail::getUserId, x -> x));
//        List<PerformanceMonthDetail> performanceMonthDetailList = new ArrayList<>();
//        if (!CollectionUtils.isEmpty(groupBy)) {
//            for (String s : groupBy.keySet()) {
//                PerformanceMonth performanceMonth = new PerformanceMonth();
//                performanceMonth.setCreateTime(new Date());
//               // performanceMonth.setDepartId(s);
//                performanceMonth.setPerforTime(DateTimeUtil.getLastMonthChar6());
//                // 绩效数据命名规则：<YY>年度<部门名称><月份>绩效；
//                SysDepart sysDepart = sysDepartMapper.selectById(s);
//                performanceMonth.setName(DateTimeUtil.getLastMonthChar4() + "年度" + sysDepart.getDepartName() + DateTimeUtil.getLastMonthChar6().substring(4, 6) + "月份绩效");
//                QueryWrapper<PerformanceMonth> monthQueryWrapper = new QueryWrapper<>();
//                monthQueryWrapper.eq("depart_id",s).eq("perfor_time",DateTimeUtil.getLastMonthChar6());
//                performanceMonthMapper.delete(monthQueryWrapper);
//
//                performanceMonthMapper.insert(performanceMonth);
//
//                List<SysUser> sysUsers = groupBy.get(s);
//                for (SysUser sysUser : sysUsers) {
//                    PerformanceMonthDetail performanceMonthDetail = new PerformanceMonthDetail();
//                    performanceMonthDetail.setCreateTime(new Date());
//                    performanceMonthDetail.setPerforMonthId(performanceMonth.getId());
//                    performanceMonthDetail.setTimeScore(0f);
//                    PerformanceMonthDetail detail = postMap.get(sysUser.getId());
//                    performanceMonthDetail.setUserId(sysUser.getId());
//                    if (detail != null) {
//                        performanceMonthDetail.setPostPreforName(detail.getPostPreforName());
//                        performanceMonthDetail.setPostScore(detail.getPostScore());
//                    }
//
//                    TaskBaseModel taskBaseModel = taskMap.get(sysUser.getUsername());
//                    if (taskBaseModel != null) {
//                        performanceMonthDetail.setTimeScore(taskBaseModel.getScore());
//                    }
//
//                    taskBaseModel = taskMap.get(sysUser.getId());
//                    if (taskBaseModel != null) {
//                        performanceMonthDetail.setTimeScore(performanceMonthDetail.getTimeScore() + taskBaseModel.getScore());
//
//                    }
//
//                    performanceMonthDetailList.add(performanceMonthDetail);
//                }
//            }
//
//            if (!CollectionUtils.isEmpty(performanceMonthDetailList)) {
//                performanceMonthDetailService.saveBatch(performanceMonthDetailList);
//
//            }
//        }

        // taskBaseModelList  和 performanceMonthDetail 合并
    }

    public static void main(String[] args) {
        System.out.println("201206".substring(4,6));
    }
}
